package com.banksystem.Jwt;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

public class JwtKit {

	public static String header = "Authorization"; // 默认请求头标识符
	public static String tokenPrefix = "Bearer ";//默认token前缀
	public static String secret = "AF17BC3B4A86A96A0F053A7E5F7C18BA"; // 默认私钥
	public static Long expiration = 7200L; // 默认失效时间(秒) 7200是两个小时
	
	/*
	 *通过 用户名密码获取token
	 */
	public static String getToken(String username){
		String token = createToken(username);
		return tokenPrefix + token;
	}
	
	/*
	 * 根据用户信息生成token
	 */
	private static String createToken(String username){
		Map<String, Object> claims = new HashMap<String,Object>();
		claims.put("sub", username);
		return createToken(claims);
	}
	
	/*
	 * 根据claims信息创建Token
	 */
	private static String createToken(Map<String, Object> claims){
		return Jwts.builder().setClaims(claims).setExpiration(generateExpirationDate())
				.signWith(SignatureAlgorithm.HS512, secret).compact();
	}
	
	/*
	 * 生成token的过期时间
	 */
	private static Date generateExpirationDate(){
		return new Date(System.currentTimeMillis() + expiration * 1000);
	}
	
	/*
	 * 用 旧token替换新的token
	 */
	public static String refreshToken(String token){
		//String jwttoken = token.substring(tokenPrefix.length(), token.length());
		if(isTokenExpired(token)){//如果已经过期
			//解析出用户名
//			String username  = getJwtUser(token);
//			return createToken(username);//创建新的token
			return null;
		}
		return token;
	}
	
	/*
	 * 判断token是否过期
	 */
	private static Boolean isTokenExpired(String token){
		final Date time = getExpirationDateFromToken(token);
		if(time == null){
			return true;
		}
		//当且仅当此 Date 对象表示的瞬间比 when 表示的瞬间早，才返回true
		return time.before(new Date());
	}
	
	/*
	 * 获取token的过期时间
	 */
	private static Date getExpirationDateFromToken(String token){
		//将Token信息解析成Claims
		Claims claims = getClaimsFromToken(token);
		//解析结束
		Date date;
		try {
			date = claims.getExpiration();			
		} catch (Exception e) {
			date = null;
		}
		return date;
	}
	
	/*
	 * 从用户Token中获取用户名信息
	 */
	public static String getJwtUser(String token){
		String jwtUser = null;
		try {
			Claims claims = getClaimsFromToken(token);
			jwtUser = claims != null? claims.getSubject() : null;	
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			return jwtUser;
		}
	}
	
	/*
	 * 将Token信息解析成Claims
	 */
	private static Claims getClaimsFromToken(String token) {
		Claims claims;
		try {
			claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
		} catch (Exception e) {
			claims = null;
		}
		return claims;
	}
}
